<template>
  <div class="form-rules">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-descriptions title="员工档案新增" border :column="3" size="medium">

        <el-descriptions-item v-for="name in list" :key="name" border :label="title[name].label">
          <el-form-item :prop="name">

            <el-input
              v-if="'input' === title[name].form"
              v-model="form[name]"
              clear="input-item"
              :maxlength="title[name]?.maxlength ? title[name]?.maxlength : ''"
              :placeholder="title[name].placeholder"
              :disabled="title[name].disabled"
              :type="title[name].type"
              :show-password="title[name].type === 'password'"
              auto-complete="new-password"
            />

            <el-upload
              v-else-if="'img' === title[name].form"
              class="avatar-uploader"
              :action="action"
              :on-exceed="exceed"
              :show-file-list="false"
              :on-success="($event) => handleAvatarSuccess($event, name)"
              :before-upload="beforeAvatarUpload"
              :data="title[name].data"
            >
              <div v-if="form[name]" class="avatar">
                <img :src="form[name]" class="avatar-img">
              </div>
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>

            <el-upload
              v-else-if="'file' === title[name].form"
              class="upload-demo"
              drag
              :on-exceed="exceed"
              :action="action"
              :on-success="($event) => handleAvatarSuccess($event, name)"
              :limit="1"
              :before-upload="beforeUpload"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div slot="tip" class="el-upload__tip">不能超过2MB的文件</div>
            </el-upload>

            <el-date-picker
              v-else-if="'date' === title[name].form"
              v-model="form[name]"
              value-format="yyyy-MM-dd"
              format="yyyy 年 MM 月 dd 日"
              align="right"
              type="date"
              placeholder="点击选项日期"
              :picker-options="pickerOptions"
              :disabled="title[name].disabled"
              @click="getDate"
            />

            <el-select
              v-else-if="'choose' === title[name].form"
              v-model="form[name]"
              :filterable="title[name].remote"
              :remote="title[name].remote"
              :focus="($event) => remoteMethod($event, name)"
              :remote-method="($event) => remoteMethod($event, name)"
              :placeholder="title[name].placeholder"
              @change="($event) => change($event, name)"
            >
              <el-option
                v-for="item in title[name].options"
                :key="item.id"
                :label="item[title[name].labelItem]"
                :value="item[title[name].value]"
              />
            </el-select>

            <el-cascader
              v-else-if="'domicile_id' === title[name].form || 'cascader' === title[name].form"
              v-model="form[name]"
              :placeholder="title[name].placeholder"
              :props="{ expandTrigger: 'hover' }"
              :options="options"
              :clearable="true"
              @change="($event) => handleChange($event, name)"
            />

            <template v-else-if="'check' === title[name].form">
              <div class="check-box">
                <el-radio
                  v-for="item in title[name].options"
                  :key="item.id"
                  v-model="form[name]"
                  :disabled="title[name].disabled"
                  :label="item.id"
                >
                  {{ item.name }}</el-radio>
              </div>

              <div v-if="'certificate' === name && form.certificate == 1">
                <el-button type="text" @click="determine">新增证书<i class="el-icon-plus" />
                </el-button>
                <el-popover v-if="form.certificate_list.length > 0" placement="right" width="700" trigger="click">
                  <el-table :data="form.certificate_list">
                    <el-table-column
                      width="150"
                      property="name"
                      label="证书名称"
                    />
                    <el-table-column
                      width="300"
                      label="证书链接"
                      property="attachment"
                    >
                      <template slot-scope="scope">
                        <span>{{ scope.row.attachment.path }}</span>
                      </template></el-table-column>
                    <el-table-column
                      width="120"
                      property="expire_at"
                      label="到期时间"
                    />
                    <el-table-column
                      width="50"
                      property="expire_at"
                      label="操作"
                    >
                      <template slot-scope="scope">
                        <el-button type="text" @click="edit(scope.row)">编辑</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-button slot="reference" type="text">查看证书<i class="el-icon-view" /></el-button>
                </el-popover>
              </div>
            </template>

            <el-cascader
              v-else-if="title[name].form === 'chooseMany'"
              :props="title[name].props"
              :placeholder="title[name].placeholder"
              :options="Array.isArray(title[name].options)?title[name].options:[]"
              @change="($event) => handleChange($event, name)"
            />

            <el-cascader
              v-else-if="title[name].form=== 'address'"
              :placeholder="title[name].placeholder"
              :props="title[name].props"
              @change="($event) => handleChange($event, name)"
            />

            <div v-else-if="'emergency_contact' === title[name].form">
              {{ form.emergency_contact.relation }}
              {{ form.emergency_contact.name }}
              {{ form.emergency_contact.phone }}
              <el-button
                type="text"
                @click="
                  emergencyDialogVisible = title[name].disabled ? false : true
                "
              >
                {{
                  form.emergency_contact.name ||
                    form.emergency_contact.phone ||
                    form.emergency_contact.relation
                    ? "编辑"
                    : "新增"
                }}
              </el-button>
            </div>
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
      <el-dialog
        title="紧急联系人"
        :visible.sync="emergencyDialogVisible"
        :close-on-click-modal="false"
        width="40%"
      >
        <el-form :inline="true" :model="form.emergency_contact" class="demo-form-inline">
          <el-form-item label="姓名">
            <el-input v-model="form.emergency_contact.name" placeholder="姓名" />
          </el-form-item>
          <el-form-item label="关系">
            <el-input v-model="form.emergency_contact.relation" placeholder="关系" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="form.emergency_contact.phone" maxlength="11" placeholder="联系方式" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="openEmergency()">取 消</el-button>
          <el-button
            type="primary"
            @click="saveContact()"
          >确定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="证书"
        :visible.sync="certificate"
        :close-on-click-modal="false"
        width="30%"
      >
        <el-form
          ref="certificate"
          :rules="rulesCertificate_item"
          :model="certificate_item"
          label-width="80px"
          label-position="right"
        >
          <el-form-item label="证书名称" prop="name" :style="{ 'margin-bottom': '30px !important' }">
            <el-input v-model="certificate_item.name" type="text" placeholder="请输入证书名称" maxlength="15" show-word-limit />
          </el-form-item>
          <el-form-item label="证书文件" prop="attachment" :style="{ 'margin-bottom': '20px !important' }">
            <el-upload
              class="upload-demo"
              :action="action"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :limit="1"
              :on-exceed="exceed"
              :file-list="fileList"
              :on-success="certificateSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip">且不超过2MB的文件/图片</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="到期日期" prop="expire_at">
            <el-date-picker
              v-model="certificate_item.expire_at"
              value-format="yyyy-MM-dd"
              format="yyyy 年 MM 月 dd 日"
              type="date"
              :editable="false"
              placeholder="点击选项日期"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="certificate = false">取 消</el-button>
          <el-button type="primary" @click="saveCertificate">确定</el-button>
        </span>
      </el-dialog>
      <div class="submit-btn">
        <el-button type="primary" plain @click="submit">提交</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { userExcelImport } from '@/api/v2/entry.js'
import { getFieldsList } from '@/api/customFields.js'
import { mixins } from './mixins.js'
export default {
  mixins: [mixins],
  data() {
    return {
      fileList: [],
      rulesCertificate_item: {
        name: [
          {
            required: true,
            trigger: ['change', 'blur'],
            message: '请输入证书名称'
          }
        ], // 证书名称
        attachment: [
          {
            required: true,
            trigger: ['change'],
            message: '请上传证书附件'
          }
        ], // 附件
        expire_at: [
          {
            trigger: ['change'],
            message: '请选择到期时间'
          }
        ] // 到期时间（选填）
      }, // 证书规则
      certificate_item: {
        name: '', // 证书名称
        attachment: null, // 附件
        expire_at: '' // 到期时间（选填）
      },
      certificate: false, // 证书弹窗
      emergencyDialogVisible: false,
      date_picker: false, // 显示日期选择
      show: false,
      fields: [],
      blacklist: ['86'] // 黑名单
    }
  },
  computed: {
    filteredData() {
      return this.fields.filter(item => !this.blacklist.includes(item.id.toString()))
    },
    options() {
      console.log(1111)
      const { options } = this.title.room_id
      if (!Array.isArray(options)) return []
      return options.reduce((res, opt) => {
        const { address, id, room } = opt
        const children = room.filter(r => r.number - r.userCompany.length > 0).map(r => {
          return { label: r.name, value: r.id }
        })
        if (children.length > 0) {
          res.push({
            label: address,
            value: id,
            children: children
          })
        }
        return res
      }, [])
    }
  },
  mounted() {
    // console.log(this.title.room_id)
    // console.log(this.title)
  },
  created() {
    this.getFields()
  },
  methods: {
    async getFields() {
      try {
        const data = [
          'user_details', 'user_companys'
        ]
        const res = await getFieldsList({ table: JSON.stringify(data) })
        if (res.status === 'success') {
          this.fields = res.data
        }
      } catch (error) {
        if (error.response?.data.code === 400) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        } else if (error.response?.status === 422) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        }
      }
    },
    saveContact() {
      if (this.form.emergency_contact.name && this.form.emergency_contact.relation && this.form.emergency_contact.phone) {
        this.emergencyDialogVisible = false
      } else {
        this.$message({
          message: '请填写紧急联系人完整信息',
          type: 'error'
        })
      }
    },
    openEmergency() {
      console.log(1212121)
      // this.form.emergency_contact.relation = ''
      // this.form.emergency_contact.name = ''
      // this.form.emergency_contact.phone = ''
      this.emergencyDialogVisible = false
    },
    edit(value) {
      this.certificate_item = value
      this.fileList = [
        {
          name: value.attachment.name,
          response: {
            data: {
              path: value.attachment.path,
              res: value.attachment.name
            }
          }
        }
      ]
      this.certificate = true
    },
    // 文件上传成功
    certificateSuccess(response) {
      const {
        data: { path, res }
      } = response
      this.certificate_item.attachment = {
        path: path,
        name: res
      }
    },
    // 移除不要的链接
    handleRemove(file, fileList) {},
    // 保存证书
    saveCertificate() {
      this.$refs.certificate.validate((valid) => {
        if (valid) {
          this.form.certificate_list.push(this.certificate_item)
          console.log(this.form)
          this.fileList = []
          this.certificate_item = this.$options.data().certificate_item
          this.$refs.certificate.clearValidate()
          this.certificate = false
          console.log(this.form)
        }
      })
    },
    // 打开
    determine() {
      this.certificate = true
    },

    postEmergencr() {
      this.form.emergency_contact = this.$options.data().form.emergency_contact
      this.emergencyDialogVisible = false
    },
    async submitApi(params) {
      try {
        userExcelImport
        const res = await userExcelImport(params)
        if (res.status === 'success') {
          this.$message({
            type: 'success',
            message: '创建成功!'
          })
          this.$confirm('是否在次添加?', '创建成功', {
            confirmButtonText: '前往查看',
            cancelButtonText: '再次添加',
            type: 'success',
            center: true
          })
            .then(() => {
              this.$router.push({
                name: 'PersonnelFiles'
              })
            })
            .catch(() => {
              this.form = this.$options.data().form
              this.$refs.form.clearValidate()
              this.$message({
                type: 'info',
                message: '再次添加'
              })
            })
        }
      } catch (error) {
        if (error.response?.data.code === 400) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        } else if (error.response?.status === 422) {
          this.$message({
            type: 'error',
            message: error.response.data.message
          })
        }
      }
    },

    // 提交按钮
    submit() {
      const params = {}
      this.list.forEach((item) => {
        if (this.form[item] !== 0 && !this.form[item]) {
          if (this.rules[item] && !this.rules[item][0].required) {
            delete this.rules[item]
          }
        } else {
          if (item === 'emergency_contact' && this.form[item].name) {
            params[item] = JSON.stringify(this.form[item])
          } else {
            params[item] = this.form[item]
          }
        }
      })
      if (this.form.certificate_list.length > 0) {
        params.certificate_list = JSON.stringify(this.form.certificate_list)
      }

      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 要移除的键的数组
          const keysToRemove = ['password']
          const removedKeyValuePairs = {}

          // 遍历要移除的键，将其从原始对象中删除并存储到新对象中
          keysToRemove.forEach(key => {
            if (Object.prototype.hasOwnProperty.call(params, key)) {
              removedKeyValuePairs[key] = params[key]
              delete params[key]
            }
          })

          // 获取原始 emergency_contact 的值并转换为字符串
          var emergencyContactValue = JSON.stringify(params.emergency_contact)
          // 将原始对象中的 emergency_contact 属性值替换为字符串
          params.emergency_contact = emergencyContactValue
          const datas = []
          datas.push(params)
          console.log(datas, removedKeyValuePairs, 232112311231)
          const all = {
            'data': JSON.stringify(datas),
            'password': removedKeyValuePairs.password
          }
          console.log(params, datas, 9999999999999)
          this.submitApi(all)
        } else {
          this.rules = this.$options.data().rules
          this.$message({
            message: '请填写完整信息',
            type: 'error'
          })
          return false
        }
      })
    },
    // 点击多级
    handleChange(value, name) {
      switch (name) {
        case 'department_id':
          if (value) {
            const len = value.length
            this.form[name] = value[len - 1]
            let options = this.title[name].options
            let id = {}
            for (let index = 0; index < len; index++) {
              id = options.find((item) => item.id === [value[index]])
              if (id.children) {
                options = id.children.length > 0 ? id.children : []
              }
            }
            console.log(this.title.leader_id)
            this.title.leader_id.options = [
              {
                id: id.leader.id,
                name: id.leader.username
              }
            ]
            this.form.leader_id = id.leader.id
          }
          break
        case 'domicile_id':
          if (value) {
            const len = value.length
            this.form[name] = value[len - 1].id / 1
          }
          break
        case 'room_id':
          if (value) {
            const len = value.length
            this.form[name] = value[len - 1]
            let option = this.title[name].options
            console.log(option, '340')
            let room_id = {}
            for (let index = 0; index < len; index++) {
              room_id = option.find((item) => item.id === [value[index]])
              console.log(room_id, 'room_id')
              if (room_id.room) {
                option = room_id.room.length > 0 ? room_id.room : []
                console.log(option, '345')
              }
            }
          }
          break
      }
    },
    change(value, name) {
      name = name + ''
      this.form[name] = value
    },
    // 远程搜索
    async remoteMethod(value, name) {
      this.title[name].options = []
      try {
        const { data } = await this.post[name]({
          search: value,
          page: 1,
          paginate: 50
        })
        this.title[name].options = data.data
      } catch (error) { }
    },
    // 点击输入框
    getDate(name) {
      if (!this.title[name].disabled) return
      this.date = name
      this.date_picker = true
    },
    // 图片上传成功
    handleAvatarSuccess(res, name) {
      console.log(res, 666666)
      const { data } = res
      if (data?.analysis?.error_code) {
        const m = {
          identity_card_front: '身份证正面(人像面)识别失败 请重新上传',
          identity_card_reverse: '身份证反面(国徽面)识别失败 请重新上传'
        }

        const errMsg = m[name] ?? '上传的信息识别有误请重新上传'
        this.$notify.error({
          title: '错误',
          message: errMsg
        })
        return
      }
      switch (name) {
        case 'identity_card_front':
          this.form.identity_card = data.analysis.result.number
          this.form.name = data.analysis.result.name
          this.form.birthday_at = data.analysis.result.birth
          const age = this.getAge(data.analysis.result.birth)
          this.form.age = age / 1
          this.form.gender = data.analysis.result.sex
          break

        case 'identity_card_reverse':
          this.form.identity_card_at = data.analysis.result.valid_to
          break
      }
      this.form[name] = data.path
    }
  }
}
</script>
<style lang="scss" scoped>
:deep(.el-descriptions-item__label) {
  text-align: center !important;
}

.submit-btn {
  display: flex;
  flex-direction: row-reverse;
  padding: 20px 0;
}

.el-descriptions-item__cell {
  padding: 10px 10px 25px 10px !important;
}

:deep(.el-form-item) {
  margin: 10px 0 !important;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.form-rules {
  width: 100%;
  // display: flex;
  flex-direction: row;
  justify-content: center;
  padding: 50px;
  background-color: #fff;
  overflow-x: auto;
}

.input-item {
  width: 50%;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-img {
  max-width: 100%;
  max-height: 100%;
}
</style>
